package com.code2roc.jarmanage.firewall;

import com.code2roc.jarmanage.util.CMDUtil;

import java.text.MessageFormat;

public class LinuxFireWallService implements FireWallService {

    @Override
    public boolean addRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("firewall-cmd --permanent --add-port={0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd --reload";
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd  --list-ports";
        String result = CMDUtil.executeLinuxCommand(command);
        if (result.indexOf(port + "/" + protocol)>=0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean deleteRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("firewall-cmd --permanent --remove-port={0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd --reload";
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd  --list-ports";
        String result = CMDUtil.executeLinuxCommand(command);
        if (result.indexOf(port + "/" + protocol)<0) {
            return true;
        } else {
            return false;
        }
    }
}
